package com.habdqn.easybuy.web.front.order;

import com.habdqn.easybuy.entity.Order;
import com.habdqn.easybuy.entity.OrderDetail;
import com.habdqn.easybuy.entity.Shop;
import com.habdqn.easybuy.entity.User;
import com.habdqn.easybuy.service.OrderDetailService;
import com.habdqn.easybuy.service.OrderService;
import com.habdqn.easybuy.service.ShopService;
import com.habdqn.easybuy.service.impl.OrderDetailServiceImpl;
import com.habdqn.easybuy.service.impl.OrderServiceImpl;
import com.habdqn.easybuy.service.impl.ShopServiceImpl;
import com.habdqn.easybuy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/12/3
 */
@WebServlet(name = "OrderAddServlet",urlPatterns = "/order/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("currentUser");
        // 获取订单数据
        Order order = new Order();
        order.setUserId(user.getId());
        order.setCreateTime(new Date());
        order.setStatus(1);
        // 获取订单总价
        String strCost = request.getParameter("jstext");
        if (StringUtils.isNotBlank(strCost)){
            order.setCost(Double.parseDouble(strCost));
        }
        // 执行新增订单操作
        OrderService orderService = new OrderServiceImpl();
        orderService.insert(order);

        // 获取订单详情数据
        // 获取选中的购物车记录编号
        String[] ops = request.getParameterValues("op");
        // 将id组装成用“,”分隔的字符串
        String shopIds = String.join(",",ops);
        ShopService shopService = new ShopServiceImpl();
        List<Shop> shopList = shopService.queryByIds(shopIds);
        // 利用对应的购物编号，组装对应的订单详情内容
        OrderDetailService orderDetailService = new OrderDetailServiceImpl();
        for (Shop shop : shopList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setProductId(shop.getProductId());
            orderDetail.setProductQuantity(shop.getProductQuantity());
            orderDetailService.insert(orderDetail);
        }
        // 跳转订单完成页面
        request.getRequestDispatcher("/WEB-INF/front/shopping-result.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
